

package cn.shengchao.controler;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.shengchao.base.utils.HttpKit;
import cn.shengchao.util.helper.LoginHelper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.continew.starter.cache.redisson.util.RedisUtils;
import top.continew.starter.log.annotation.Log;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

import static cn.shengchao.base.constant.Constants.RedisKey.VIDEO_AUTH_KEY;

@Tag(name = "播放校验")
@Slf4j
@RestController
@CrossOrigin("${project.cross-origin}")
@RequestMapping("video/auth")
public class AuthController {


    @Log(ignore = true)
    @SaIgnore
    @RequestMapping
    public ResponseEntity auth() {
        try {
            String aliOriginRealUrl = HttpKit.getRequest().getHeader("Ali-Origin-Real-Url");
            if (aliOriginRealUrl.contains(".m3u8")) {
                Long userId = LoginHelper.getUserId();
                String userAgent = RedisUtils.get(VIDEO_AUTH_KEY + userId);
                String requestUserAgent = HttpKit.getRequest().getHeader("User-Agent");
                if (userAgent != null) {
                    if (userAgent.equals(requestUserAgent)) {
                        return new ResponseEntity("success", null, 200);
                    } else {
                        return new ResponseEntity("fail", null, 403);
                    }
                } else {
                    RedisUtils.set(VIDEO_AUTH_KEY + userId, requestUserAgent, Duration.of(10, ChronoUnit.MINUTES));
                }
            }
        } catch (Exception e) {
            return new ResponseEntity("fail", null, 403);
        }
        return new ResponseEntity("success", null, 200);
    }
}
